<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Admin\Store;
use App\Services\Admin\UserVip;
use App\Http\Requests\Admin\TeacherControler\doRule;
use App\Models\UserIntegral as UserIntegralModel;
use App\Services\Admin\UserIntegral;
use App\Http\Requests\Admin\UserIntegralRequest;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class UserIntegralController extends Controller
{
    public function index()
    {
        $result = [
            'result'=>UserIntegral::lists(),
            'select_store'=>Store::where_lists(),
            'store_id'=>\request()->get('store_id'),
            'sear_value'=>\request()->get('sear_value'),
            'status'=>\request()->get('status'),
            'start_time'=>\request()->get('start_time'),
            'end_time'=>\request()->get('end_time'),
        ];

        return view('admin.user_integral.index', $result);
    }

    public function add()
    {
        $result = [
            'select_store'=>Store::where_lists(),
            'select_id' => '',
        ];

        return view('admin.user_integral.edit',$result);
    }

    public function edit(Request $request, $id)
    {
        //dd($id);
        $info = UserIntegral::info($id);

        $result = [
            'id'=>$id,
            'select_store'=>Store::where_lists(),
            'select_id' => $info->store_id,
            'result'=> $info,
        ];

        return view( 'admin.user_integral.edit', $result);

    }

    public function do(Request $request)
    {
        if ($request->ajax()) {

            $input = $request->all();

            if(!in_array($input['status'],['1', '2', '3']))return self::fail('状态参数有误!');

            DB::beginTransaction();

            try {

                if (empty($input['id'])) {

                    unset($input['id']);

                    UserIntegral::add($input);

                } else {

                    if(!UserIntegral::edit($input['id'], $input))throw new \Exception('已操作过了!');

                }

                DB::commit();

            }catch(\Exception $e){

                //接收异常处理并回滚
                DB::rollBack();

                return $this->fail($e->getMessage());

            }

            return self::success([]);
        }
    }
}
